import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const categoryStore = createSlice({
  name: "category",
  initialState: {
    categoryCode: "",
    categoryList: [],
  },
  reducers: {
    setCategoryList(state, action) {
      state.categoryList = action.payload;
    },
    setCategoryCode(state, action) {
      state.categoryCode = action.payload;
    },
  },
});

const { setCategoryList, setCategoryCode } = categoryStore.actions;
const reducer = categoryStore.reducer;

function fetchCategoryList() {
  return async (dispatch) => {
    const res = await axios.get("http://localhost:9000/category/list");
    dispatch(setCategoryList(res.data.data));
    dispatch(setCategoryCode(res.data.data[0].code));
  };
}

export { setCategoryCode };
export { fetchCategoryList };
export default reducer;
